package com.syedu.day15.homework;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * description：多线程同步并发原子性案例
 * @author Administrator
 * @date 2022/4/1 15:11
 */
public class TicketThread {
    public static void main(String[] args) {
        Runnable r = new SellTicket();
        Thread t1 = new Thread(r, "窗口A");
        Thread t2 = new Thread(r, "窗口B");
        Thread t3 = new Thread(r, "窗口C");
        t1.start();
        t2.start();
        t3.start();
    }
}

class SellTicket implements Runnable {
    private int tickets = 100;

    Lock lock = new ReentrantLock();

    @Override
    //public synchronized void run() {

    public void run() {
        while (true) {
            ///synchronized (this) {
            try {
                lock.lock();//加锁
                System.out.println(Thread.currentThread().getName() + ",正在出票...");
                if (tickets > 0) {
                    tickets--;
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "售出第[" + (100 - tickets) + "]张票...");
                } else {
                    System.out.println("票已售完...");
                    break;
                }
            } finally {
                lock.unlock();//解锁
            }
        }
    }
}